package com.sgq.vue.controller.picture;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sgq.vue.entity.picture.Picture;
import com.sgq.vue.entity.picture.Plate;
import com.sgq.vue.entity.picture.Tag;
import com.sgq.vue.result.Result;
import com.sgq.vue.service.picture.PictureService;
import com.sgq.vue.service.picture.PlateService;
import com.sgq.vue.service.picture.TagService;
import com.sgq.vue.service.system.FileService;
import com.sgq.vue.utils.system.MySecurityContextHolder;
import com.sgq.vue.vo.query.picture.PictureQueryVo;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author: 83778
 * @date: 2024-01-04 17:41
 * @desc:
 */
@Api(tags = "图片操作")
@RestController
@RequestMapping("/api/picture/manager")
public class PictureController {

    @Autowired
    private FileService fileService;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private PlateService plateService;

    @Autowired
    private TagService tagService;
    /**
     * 文件上传
     * @param file
     * @param plateName
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file, String plateName){
        //返回上传到oss的路径
        String url = fileService.upload(file,plateName);
        return Result.ok(url).message("文件上传成功");
    }

    @PostMapping("/add")
    @Transactional
    public Result add(@RequestBody Picture picture){
        String [] urls = picture.getUrl().split(",");
        for (String url : urls) {
            Picture temp = new Picture();
            BeanUtils.copyProperties(picture,temp);
            temp.setUrl(url);
            pictureService.save(temp);
        }
        //找到对应分区 对total 加减
        Plate plate = plateService.getById(picture.getPlateId());
        Integer total = plate.getTotal();
        plate.setTotal(total + urls.length);
        plateService.updateById(plate);
        return Result.ok("插入完毕");
    }

    @DeleteMapping("/delete/{id}")
    @Transactional
    public Result delete(@PathVariable Long id){
        //先获取分区id
        Picture picture = pictureService.getById(id);
        boolean b = pictureService.removeById(id);
        //获取分区id
        Plate plate = plateService.getById(picture.getPlateId());
        Integer total = plate.getTotal();
        plate.setTotal(total - 1);
        plateService.updateById(plate);
        return Result.ok(b);
    }

    @DeleteMapping("/delete")
    public Result removeBatchByIds(@RequestParam("ids") List<Long> ids){
        //先获取分区id
        boolean b = pictureService.removeBatchByIds(ids);
        return Result.ok(b);
    }

    /**
     * 查询所有图片，不限制上传者
     * @param pictureQueryVo
     * @return
     */
    @GetMapping("/list")
    public Result list(PictureQueryVo pictureQueryVo){
        IPage<Picture> page  = pictureService.findByPage(pictureQueryVo);
        return Result.ok(page);
    }

    @PutMapping("/editPictureTag/{pictureId}/{tags}")
    public Result editPictureTag(@PathVariable("pictureId") Long pictureId,
                                 @PathVariable("tags") String tags,
                                 @RequestParam("newTagName") String newTagName){
        //如果是新增操作，则获取newTagName，创建tag
        if(tags.contains("undefined")){
            Tag tag = new Tag();
            tag.setCreateBy(MySecurityContextHolder.getSysUsername());
            tag.setName(newTagName);
            //先判断是否存在同名标签，如果存在，直接使用已存在的标签id，否则创建新的标签
            LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Tag::getName,tag.getName());
            //查询tag
            Tag one = tagService.getOne(queryWrapper);
            if (!ObjectUtils.isEmpty(one)){
                Long id = one.getId();
                tags = tags.replace("undefined", id.toString());
            }else {
                //新增tag
                boolean save = tagService.save(tag);
                if (save){
                    Long id = tag.getId();
                    tags = tags.replace("undefined", id.toString());
                }else {
                    return Result.error().message("添加tag失败");
                }
            }
        }
        boolean b = pictureService.editPictureTag(pictureId,tags);
        return Result.ok(b);
    }

}
